package operate;

import book.Book;
import book.BookList;
import user.User;
import java.util.Scanner;

public class Return implements IOperate{
    /**
     * 功能：还书
     * 让用户输入要还的书
     * 判断有没有
     * 有：
     *  把由已借出改为未借出
     *  BookList文件同步操作
     *  没有：
     *  打印：
     * 参数：无
     * 返回类型：void
     */

    @Override
    public void operate(User user, BookList bookList) {
        System.out.println("请输入要归还的书：");
        Scanner sc=new Scanner(System.in);
        String bookName=sc.nextLine();
        boolean flag =false;//标记
        for (int i = 0; i < bookList.bookLists.size(); i++)
        {
            if(bookList.bookLists.get(i).getName().equals(bookName)&&bookList.bookLists.get(i).isBorrowed())
            {
                Book book =bookList.bookLists.get(i);
                removeBook(bookList,book);//删除借阅信息
                book.setBorrowed(false);
                System.out.println("归还成功");
                int p = user.getPoint();//添加积分
                user.setPoint(++p);
                flag =true;
                break;
            }
        }
        if(!flag) System.out.println("你未借阅在此书");
    }

    //根据书名从历史记录删除归还成功的书籍
    private void removeBook(BookList bookList,Book book)
    {
        for(int i=0;i<bookList.HistoryBorrowingBookLists.size();i++)
        {
            String name = bookList.HistoryBorrowingBookLists.get(i).getName();
            if(name.equals(book.getName()))
            {
                bookList.HistoryBorrowingBookLists.remove(i);
                break;
            }
        }
    }
}
